import React, { useState, useEffect } from 'react'
import { Table, Tooltip, Tag, Switch, Image, Button, Upload } from 'antd'
import { fetchItems } from '@/api/item'
import SearchBar from '@/components/SearchBar';
import { utils, writeFileXLSX, read } from 'xlsx';
import { useNavigate } from 'react-router-dom';
export default function ItemLists() {
  const navigate = useNavigate();
  // 请求列表参数 分页和搜索
  let page = 1;
  let pageSize = 10;
  let searchParams = {};
  const [total, setTotal] = useState(0);
  const [items, setItems] = useState([]);
  const getItems = () => {
    fetchItems({
      page,
      pageSize,
      ...searchParams
    }).then(res => {
      if (res.data.code === 200) {
        setTotal(res.data.data.total);
        setItems(res.data.data.lists);
      }
    })
  }

  useEffect(() => {
    getItems()
  }, [])
  // 行内修改商品上下架
  const switchItemOnSale = (id: number, onSale: boolean) => {
  }
  // 定义表格列
  const columns = [
    {
      title: '商品名',
      dataIndex: 'itemName',
      key: 'itemName'
    },
    {
      title: '描述',
      dataIndex: 'desc',
      render(desc: string) {
        return (
          <Tooltip title={desc}>
            <span>
              {desc.substring(0, 15) + '...'}
            </span>
          </Tooltip>
        )
      },
      key: 'desc'
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price'
    },
    {
      title: '销量',
      dataIndex: 'sale',
      render(sale: number) {
        return (
          <Tag color={sale > 500 ? 'red' : 'green'}>
            {sale}
          </Tag>
        )
      },
      key: 'sale'
    },
    {
      title: '上下架',
      dataIndex: 'onsale',
      render(onsale: boolean, row: any) {
        return <Switch checked={onsale} checkedChildren="上架" unCheckedChildren="下架" onChange={
          (checked) => {
            switchItemOnSale(row.id, onsale)
          }
        } />
      },
      key: 'onsale'
    },
    {
      title: '封面',
      dataIndex: 'thumb',
      render(thumb: string) {
        return (
          <Image src={thumb} width={50} />
        )
      },
      key: 'thumb'
    },
    {
      title: '上架时间',
      dataIndex: 'createAt',
      key: 'createAt'
    },
    {
      title: '操作',
      render: (row: any) => {
        return (
          <>
            <Button 
              onClick={
                () => {
                  updateItem(row.id)
                }
              }
              size='small' type='primary'>编辑</Button>
            <Button size='small' danger type='primary'>删除</Button>
          </>
        )
      },
      key: 'action'
    }
  ]
  // 修改商品
  const updateItem = (id: number) => {
    navigate(`/itemUpdate?id=${id}`)
  }
  // 列表分页
  const pagination = {
    defaultCurrent: page,
    defaultPageSize: pageSize,
    total,
    onChange: (_page: number, _pageSize: number) => {
      // 修改page和pageSize
      page = _page;
      pageSize = _pageSize;
      getItems()
    }
  }
  // 搜索功能
  const onSearch = (_searchParams: any) => {
    searchParams = _searchParams;
    getItems()
  }
  // 下载模板 导出excel
  const exportFile = () => {
    const data = [
      {
        商品名: '商品',
        商品价格: '777',
        描述: '这是描述'
      }
    ]
    const ws = utils.json_to_sheet(data);
    const wb = utils.book_new();
    utils.book_append_sheet(wb, ws, "Data");
    writeFileXLSX(wb, "商品表.xlsx");
  }
  // 批量新增商品
  const uploadFile = (file) => {
    const fd = new FileReader();
    fd.readAsArrayBuffer(file)
    fd.onload = () => {
      // fd.result
      const wb = read(fd.result);
      const data = utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
      const _data = data.map(el => {
        return {
          itemName: el.商品名,
          price: el.商品价格,
          desc: el.描述
        }
      })
      console.log(_data);
      
    }
    return false
  }
  const [msg, setMsg] = useState('初始值');
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center' }}>
        <Button onClick={
          () => {
            navigate('/itemAdd')
          }
        }>增加</Button>
        <Upload showUploadList={false} action="#" accept='.xlsx, .xls' beforeUpload={uploadFile}>
          <Button>批量新增商品</Button>
        </Upload>
        <a href="#" onClick={
          exportFile
        }>下载模板</a>
      </div>
      <SearchBar onSearch={onSearch} />
      <Table dataSource={items} rowKey={'id'} columns={columns} pagination={pagination} />

    </div>
  )
}
